import 'package:flutter/material.dart';

enum AlertType { success, error, none }

typedef FutureFunction = Future<void> Function();

class Alert extends Dialog {
  // 消息
  final String msg;
  // 弹窗类型
  final AlertType type;
  // 确定事件
  final FutureFunction confirm;

  Alert({Key key, this.msg, this.type, this.confirm}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Center(
      child: Container(
        width: size.width / 1.5,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(
            Radius.circular(20),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Container(
              padding: EdgeInsets.all(14),
              child: Column(
                children: <Widget>[
                  _buildIcon(context),
                  _buildMsg(context),
                ],
              ),
            ),
            _buildBtn(context),
          ],
        ),
      ),
    );
  }

  /// 构建图标
  Widget _buildIcon(BuildContext context) {
    if (type == AlertType.error) {
      return Padding(
        padding: EdgeInsets.only(bottom: 14),
        child: Icon(
          Icons.highlight_off,
          size: 64,
          color: Colors.black54,
        ),
      );
    } else if (type == AlertType.success) {
      return Padding(
        padding: EdgeInsets.only(bottom: 10),
        child: Icon(
          Icons.check_circle_outline,
          size: 64,
          color: Colors.black54,
        ),
      );
    } else {
      return Container();
    }
  }

  /// 构建消息
  Widget _buildMsg(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Text(
        msg,
        style:
            Theme.of(context).textTheme.button.copyWith(color: Colors.black87),
        textAlign: TextAlign.center,
      ),
    );
  }

  /// 构建确定按钮
  Widget _buildBtn(BuildContext context) {
    return GestureDetector(
      child: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(vertical: 12.0),
        decoration: BoxDecoration(
          color: Theme.of(context).primaryColor,
          borderRadius: BorderRadius.vertical(
            bottom: Radius.circular(20),
          ),
        ),
        child: Text(
          '确定',
          style:
              Theme.of(context).textTheme.button.copyWith(color: Colors.white),
        ),
      ),
      onTap: () {
        if (confirm != null) {
          confirm().then((_) => _close(context));
        } else {
          _close(context);
        }
      },
    );
  }

  /// 关闭窗体
  _close(BuildContext context) {
    Navigator.of(context).pop();
  }
}
